<?php

namespace App\Http\Controllers;

use App\Exceptions\ReportableException;
use App\Models\User;
use App\Service\TokenService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;

class Login extends Controller
{
    //
    public function index(): \Illuminate\Http\JsonResponse
    {
        return response()->json(['message' => 'Unauthorized'], ReportableException::INVALID_CODE);
    }

    /**
     * 登录
     * @param Request $request
     * @param TokenService $tokenService
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request, TokenService $tokenService): \Illuminate\Http\JsonResponse
    {
        $credentials = $request->only('name', 'password');
        $user = User::where('name', $credentials['name'])->first();
        if (!$user || !Hash::check($credentials['password'], $user->password)) {
            return response()->json(['message' => '账号密码错误'], ReportableException::INVALID_CODE);
        }
        $user->last_login_at = date('Y-m-d H:i:s');
        $user->last_login_ip = $request->ip();
        $user->save();
        $token = $tokenService->createToken($user);
        return response()->json(['token' => $token]);
    }

    /**
     * 退出登录
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(Request $request): \Illuminate\Http\JsonResponse
    {
        $token = $request->header('Authorization');
        $tokenService = new TokenService();
        $tokenService->deleteToken($token);
        return response()->json(['message' => '退出登录成功']);
    }
}
